package it.rap.applications.property.manager.services;

import it.rap.applications.contributions.manager.services.IDownloadServiceHandler;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.rap.rwt.RWT;
import org.eclipse.rap.rwt.service.ServiceHandler;


public class ImgDownloadServiceHandler implements IDownloadServiceHandler, ServiceHandler {
	public static String ID = "ImgDownloadServiceHandler";

	public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
	        
	    String i = (String) request.getParameter( "i" );
	    if ( i == null ){
	    	i = (String) request.getAttribute( "i" );
	    }
	    // Get the file content
	    //Path path = Paths.get( filePath + fileName );
	    ClassLoader classLoader = DownloadServiceHandler.class.getClassLoader();
	    InputStream inputStream = classLoader.getResourceAsStream( "resources/" + i );
	    
	    //byte[] download = Files.readAllBytes( path  );
	    ByteArrayOutputStream download = new ByteArrayOutputStream();
	    byte[] buf = new byte[1024];
	    while( inputStream.read( buf ) != -1 ){
	      download.write( buf );
	    }
	    // Send the file in the response    
	    response.setContentType( "application/octet-stream" );
	    response.setContentLength( download.toByteArray().length );
	    String contentDisposition = "attachment; filename=\"" + i + "\"";
	    response.setHeader( "Content-Disposition", contentDisposition );
	    response.getOutputStream().write( download.toByteArray() );
		
	    Logger.getAnonymousLogger().info( "services OK" );
	}
	
	public String createDownloadUrl( String filename ) {
	  StringBuilder url = new StringBuilder();
	  url.append( RWT.getServiceManager().getServiceHandlerUrl( ImgDownloadServiceHandler.ID ) );
	  url.append( "&" ).append( "i" ).append( "=" ).append( filename );
	  return url.toString();
	}

}
